package com.fowo.api.syncAmazon.api;

import cn.hutool.core.lang.Assert;
import com.alibaba.excel.util.StringUtils;
import com.amazon.spapi.api.FbaInboundApi;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.fulfillmentinbound.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.common.model.RException;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.entity.ShopInfo;
import com.fowo.api.entity.SysCountry;
import com.fowo.api.entity.TmpFbaShipment;
import com.fowo.api.entity.TmpFbaShipmentProduct;
import com.fowo.api.mapper.TmpFbaShipmentMapper;
import com.fowo.api.model.fba.shipment.FbaShipmentVo;
import com.fowo.api.model.fba.shipment.product.FbaShipmentProductItemVo;
import com.fowo.api.model.fba.shipmenttrack.FbaShipmenttrackItemVo;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.service.impl.SysCountryServiceImpl;
import com.fowo.api.syncAmazon.util.AmazonUtil;
import com.fowo.api.syncAmazon.util.AmzDateUtils;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ShipmentService {

    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private AmazonUtil amazonUtil;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private TmpFbaShipmentMapper tmpFbaShipmentMapper;
    @Resource
    private SysCountryServiceImpl sysCountryService;

    /**
     * 创建货件计划
     * @param fbaShipmentVo
     * @throws ApiException
     */
    public InboundShipmentPlanList createShipmentPlan(FbaShipmentVo fbaShipmentVo) throws ApiException {

        final ShopInfo shopInfo = shopInfoService.getById(fbaShipmentVo.getShop());
        Assert.isTrue("SQ01".equals(shopInfo.getSellerAuthStatus()),"店铺授权异常");

        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shopInfo);

        CreateInboundShipmentPlanResponse response = fbaInboundApi.createInboundShipmentPlan(buildBody(fbaShipmentVo,shopInfo.getRegion()));

        return response.getPayload().getInboundShipmentPlans();

    }

    /**
     * 构建货件计划数据
     * @param fbaShipmentVo
     * @param countryCode
     * @return
     */
    public CreateInboundShipmentPlanRequest buildBody(FbaShipmentVo fbaShipmentVo,String countryCode){
        Address address = new Address();
        address.setName(fbaShipmentVo.getConsignerName()); //个人或企业的名称
        address.setAddressLine1(fbaShipmentVo.getStreetAddress()); //街道地址信息
        address.setCity(fbaShipmentVo.getCity()); //城市
//        address.setDistrictOrCounty(""); //区或县(非必填)
        address.setStateOrProvinceCode(fbaShipmentVo.getProvince()); //州或省的代码
        address.setCountryCode(fbaShipmentVo.getShipmentsCountry()); //国家编码
        address.setPostalCode(fbaShipmentVo.getPostcode()); //邮编

        CreateInboundShipmentPlanRequest body = new CreateInboundShipmentPlanRequest()
                .shipFromAddress(address) //收货的地址
                .labelPrepPreference(LabelPrepPreference.fromValue(fbaShipmentVo.getLabelType()))//对入境货物的标签准备的偏好。
                .shipToCountryCode(countryCode) //国家编码
                .inboundShipmentPlanRequestItems(buidInboundShipmentPlanRequestItemList(fbaShipmentVo.getList()));//货物列表
        return body;
    }

    /**
     * 构建货件商品列表
     * @return
     */
    public InboundShipmentPlanRequestItemList buidInboundShipmentPlanRequestItemList(List<FbaShipmentProductItemVo> list){
        InboundShipmentPlanRequestItemList itemList = new InboundShipmentPlanRequestItemList();
        for(FbaShipmentProductItemVo vo : list){
            InboundShipmentPlanRequestItem item = new InboundShipmentPlanRequestItem()
                    .sellerSKU(vo.getMsku())
                    .ASIN(vo.getAsin())
                    .condition(Condition.NEWITEM) //物品的状况
                    .quantity(vo.getAmountDeclared()) //数量
                    .quantityInCase(vo.getQuantityPerCarton()); //每个箱子中的物品数量（非必填）
            itemList.add(item);
        }
        return itemList;
    }

    /**
     * 创建货件
     * @param shopId
     * @param plans
     * @throws ApiException
     */
    public Map<String,String> createInboundShipment(Long shopId, InboundShipmentPlanList plans,Map<String,String> shipmentNameMap) throws ApiException {
        final ShopInfo shopInfo = shopInfoService.getById(shopId);
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);
        FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shopInfo);
        Map<String,String> shipmentIds = new HashMap();
        for(InboundShipmentPlan plan : plans){
            String shipmentName = shipmentNameMap.get(plan.getShipmentId());
            InboundShipmentRequest body = new InboundShipmentRequest()
                    .inboundShipmentHeader(buildInboundShipmentHeader(plan,shipmentName))
                    .inboundShipmentItems(buildInboundShipmentItems(plan))
                    .marketplaceId(shopInfo.getMarketplaceId()); //市场标识符。指定产品存储的市场。
            InboundShipmentResponse response = fbaInboundApi.createInboundShipment(body, plan.getShipmentId());
            shipmentIds.put(plan.getShipmentId(),response.getPayload().getShipmentId());
//            shipmentIds.add(response.getPayload().getShipmentId());
        }
        return shipmentIds;
    }

    /**
     * 入站发货信息，用于创建和更新入站发货
     * @param plan
     * @return
     */
    public InboundShipmentHeader buildInboundShipmentHeader(InboundShipmentPlan plan,String shipmentName){
        LabelPrepPreference labelPrepPreference = null;
        switch (plan.getLabelPrepType()){
            case NO_LABEL:
            case SELLER_LABEL:
                labelPrepPreference = LabelPrepPreference.SELLER_LABEL;
                break;
            case AMAZON_LABEL:
                labelPrepPreference = LabelPrepPreference.AMAZON_LABEL_ONLY;
                break;
            default:
                labelPrepPreference = LabelPrepPreference.SELLER_LABEL;
                break;
        }
        return new InboundShipmentHeader()
                .shipmentName(shipmentName)
                .shipFromAddress(plan.getShipToAddress())
                .destinationFulfillmentCenterId(plan.getDestinationFulfillmentCenterId())
                .shipmentStatus(ShipmentStatus.WORKING)
                .labelPrepPreference(labelPrepPreference);
    }

    /**
     * 入境装运项目信息的列表。
     * @param plan
     * @return
     */
    public InboundShipmentItemList buildInboundShipmentItems(InboundShipmentPlan plan){
        InboundShipmentItemList list = new InboundShipmentItemList();
        InboundShipmentItem shipmentItem;
        for(InboundShipmentPlanItem planItem : plan.getItems()){
            shipmentItem = new InboundShipmentItem()
                    .shipmentId(plan.getShipmentId())
                    .sellerSKU(planItem.getSellerSKU()) //必填
                    .fulfillmentNetworkSKU(planItem.getFulfillmentNetworkSKU()) //可选
                    .quantityShipped(planItem.getQuantity()) //必填
                    .quantityInCase(1);
            list.add(shipmentItem);
        }
        return list;
    }

    /**
     * 拉取FBA货件
     * @return
     * @throws ApiException
     */
    public List<TmpFbaShipment> getShipments() throws ApiException {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        final List<ShopInfo> shopList = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Amazon")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
//        List<String> shipmentStatusList = new ArrayList<>();
//        shipmentStatusList.add("WORKING");
//        shipmentStatusList.add("READY_TO_SHIP");
//        shipmentStatusList.add("SHIPPED");
//        shipmentStatusList.add("RECEIVING");
//        shipmentStatusList.add("CANCELLED");
//        shipmentStatusList.add("DELETED");
//        shipmentStatusList.add("CLOSED");
//        shipmentStatusList.add("IN_TRANSIT");
//        shipmentStatusList.add("DELIVERED");
//        shipmentStatusList.add("CHECKED_IN");

        Calendar cstart=Calendar.getInstance();
        cstart.add(Calendar.DATE, -7);
        Calendar cend=Calendar.getInstance();
        List<TmpFbaShipment> tmpFbaShipments = new ArrayList<>();
        for(ShopInfo shop : shopList){
            InboundShipmentList shipmentData = new InboundShipmentList();

            FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shop);

            String marketplaceId = shop.getMarketplaceId();

            GetShipmentsResponse getShipmentsResponse = fbaInboundApi.getShipments("DATE_RANGE",marketplaceId,null,null,AmzDateUtils.getOffsetDateTimeUTC(cstart),AmzDateUtils.getOffsetDateTimeUTC(cend),null);
            GetShipmentsResult payload = getShipmentsResponse.getPayload();
            if(null != payload ){
                shipmentData.addAll(payload.getShipmentData());

                if(null != payload.getNextToken()){
                    //频繁请求接口会报错
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    InboundShipmentList shipmentsNext = getShipmentsNext(fbaInboundApi, marketplaceId, getShipmentsResponse.getPayload().getNextToken());
                    shipmentData.addAll(shipmentsNext);
                }
            }
            //拉取数据完成 映射字段并组装数据
            tmpFbaShipments.addAll(buildData(shipmentData,shop));
        }
        //拉取数据完成 映射字段并组装数据
//        List<TmpFbaShipment> tmpFbaShipments = buildData(shipmentData,shop);

        return tmpFbaShipments;
    }

    public List<TmpFbaShipment> buildData(InboundShipmentList inboundShipmentList,ShopInfo shopInfo){
        if(inboundShipmentList == null || inboundShipmentList.size() < 1){
            throw new RException("FBA货件数据为空");
        }
        List<TmpFbaShipment> list = new ArrayList<>();
        for (InboundShipmentInfo info:inboundShipmentList) {
            TmpFbaShipment shipment = new TmpFbaShipment();
            shipment.setSid(shopInfo.getId());
            shipment.setCountry(shopInfo.getCountry());
            shipment.setShipmentId(info.getShipmentId());
            shipment.setShipmentName(info.getShipmentName());
            if(info.getShipmentStatus() != null){
                shipment.setShipmentStatus(info.getShipmentStatus().getValue());
            }
            Address shipFromAddress = info.getShipFromAddress();
            shipment.setName(shipFromAddress.getName());
            shipment.setCity(shipFromAddress.getCity());
            shipment.setAddressLine(shipFromAddress.getAddressLine1());
            shipment.setDistrictOrCounty(shipFromAddress.getDistrictOrCounty());
            shipment.setStateOrProvinceCode(shipFromAddress.getStateOrProvinceCode());
            shipment.setCountryCode(shipFromAddress.getCountryCode());
            shipment.setPostalCode(shipFromAddress.getPostalCode());
            shipment.setDestinationFulfillmentCenterId(info.getDestinationFulfillmentCenterId());
            if(info.getLabelPrepType() != null){
                shipment.setLabelPrepType(info.getLabelPrepType().getValue());
            }
            if(info.getBoxContentsSource() != null){
                shipment.setBoxContentsSource(info.getBoxContentsSource().getValue());
            }
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                shipment.setConfirmedNeedByDate(sim.parse(info.getConfirmedNeedByDate().replace("T"," ").replace("Z","")));
            }catch (Exception e){

            }
            BoxContentsFeeDetails estimatedBoxContentsFee = info.getEstimatedBoxContentsFee();
            if(estimatedBoxContentsFee != null){
                if(estimatedBoxContentsFee.getTotalUnits() != null){
                    shipment.setTotalUnits(estimatedBoxContentsFee.getTotalUnits());
                }
                if(estimatedBoxContentsFee.getFeePerUnit() != null){
                    shipment.setFeePerUnit(estimatedBoxContentsFee.getFeePerUnit().getValue());
                }
                if(estimatedBoxContentsFee.getTotalFee() != null){
                    shipment.setTotalFee(estimatedBoxContentsFee.getTotalFee().getValue());
                }
            }
            shipment.setCreateTime(new Date());
            shipment.setDelFlag(false);
            list.add(shipment);
        }
        return list;
    }

    /**
     * FBA货件下一页数据
     * @param fbaInboundApi
     * @param marketplaceId
     * @param nextToken
     * @return
     * @throws ApiException
     */
    public InboundShipmentList getShipmentsNext(FbaInboundApi fbaInboundApi,String marketplaceId,String nextToken ) throws ApiException {
        GetShipmentsResponse getShipmentsResponse = fbaInboundApi.getShipments("NEXT_TOKEN",marketplaceId,null,null,null,null,nextToken);
        final GetShipmentsResult payload = getShipmentsResponse.getPayload();
        InboundShipmentList shipmentData = payload.getShipmentData();
        if(StringUtils.isNotBlank(payload.getNextToken())){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            nextToken = payload.getNextToken();
            InboundShipmentList shipmentsNext = getShipmentsNext(fbaInboundApi, marketplaceId, nextToken);
            shipmentData.addAll(shipmentsNext);
        }
        return shipmentData;
    }


    /**
     * 拉取FBA货件详情
     * @return
     * @throws ApiException
     */
    public List<TmpFbaShipmentProduct> getShipmentItems() throws ApiException {

        final List<ShopInfo> shopList = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Amazon")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        Calendar cstart=Calendar.getInstance();
        cstart.add(Calendar.DATE, -7);
        Calendar cend=Calendar.getInstance();

        InboundShipmentItemList itemData = new InboundShipmentItemList();
        for(ShopInfo shop : shopList){
            FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shop);

            String marketplaceId = shop.getMarketplaceId();

            GetShipmentItemsResponse getShipmentItemsResponse = fbaInboundApi.getShipmentItems("DATE_RANGE",marketplaceId, AmzDateUtils.getOffsetDateTimeUTC(cstart),AmzDateUtils.getOffsetDateTimeUTC(cend),null);
            GetShipmentItemsResult payload = getShipmentItemsResponse.getPayload();
            if(null != payload){
                itemData.addAll(payload.getItemData());
                if(null != payload.getNextToken()){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    InboundShipmentItemList shipmentItemsNext = getShipmentItemsNext(fbaInboundApi, marketplaceId, getShipmentItemsResponse.getPayload().getNextToken());
                    itemData.addAll(shipmentItemsNext);
                }
            }

        }

        //数据拉取完成 映射字段并组装数据
        List<TmpFbaShipmentProduct> tmpFbaShipmentProducts = buildItemData(itemData);
        return tmpFbaShipmentProducts;
    }

    public List<TmpFbaShipmentProduct> buildItemData(InboundShipmentItemList inboundShipmentItems){
        if(inboundShipmentItems == null || inboundShipmentItems.size() < 1){
            throw new RException("货架详情数据为空");
        }
        Map<String, List<TmpFbaShipment>> collect = null;
        List<TmpFbaShipment> tmpFbaShipments = tmpFbaShipmentMapper.selectList(new QueryWrapper<>());
        if(tmpFbaShipments != null && tmpFbaShipments.size() > 0){
            collect = tmpFbaShipments.stream().collect(Collectors.groupingBy(TmpFbaShipment::getShipmentId));
        }
        List<TmpFbaShipmentProduct> list = new ArrayList<>();
        for (InboundShipmentItem item:inboundShipmentItems) {
            TmpFbaShipmentProduct product = new TmpFbaShipmentProduct();
            product.setShipmentId(item.getShipmentId());
            product.setCreateTime(new Date());
            product.setDelFlag(false);
            product.setFulfillmentNetworkSku(item.getFulfillmentNetworkSKU());
            product.setSellerSku(item.getSellerSKU());
            product.setQuantityShipped(item.getQuantityShipped());
            product.setQuantityReceived(item.getQuantityReceived());
            product.setQuantityInCase(item.getQuantityInCase());
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                product.setReleaseDate(sim.parse(item.getReleaseDate().replace("T"," ").replace("Z","")));
            }catch (Exception e){}
            PrepDetailsList prepDetailsList = item.getPrepDetailsList();
            List<String> prepInstruction = new ArrayList<>();
            List<String> prepOwner = new ArrayList<>();
            if(prepDetailsList != null){
                for (PrepDetails details:prepDetailsList) {
                    if(details.getPrepInstruction() != null){
                        prepInstruction.add(details.getPrepInstruction().getValue());
                    }
                    if(details.getPrepOwner() != null){
                        prepOwner.add(details.getPrepOwner().getValue());
                    }
                }
                if(prepInstruction != null && prepInstruction.size() > 0){
                    product.setPrepInstruction(prepInstruction == null ? "" : Joiner.on(",").join(prepInstruction));
                }
                if(prepOwner != null && prepOwner.size() > 0){
                    product.setPrepOwner(prepOwner == null ? "" : Joiner.on(",").join(prepOwner));
                }
            }
            if(collect != null){
                List<TmpFbaShipment> tmpFbaShipments1 = collect.get(product.getShipmentId());
                product.setParentFbaShipment(tmpFbaShipments1.get(0).getId());
            }
            list.add(product);
        }
        return list;
    }

    /**
     * FBA货件详情过下一页数据
     * @param fbaInboundApi
     * @param marketplaceId
     * @param nextToken
     * @return
     * @throws ApiException
     */
    public InboundShipmentItemList getShipmentItemsNext(FbaInboundApi fbaInboundApi,String marketplaceId,String nextToken ) throws ApiException {
        GetShipmentItemsResponse getShipmentItemsResponse = fbaInboundApi.getShipmentItems("NEXT_TOKEN", marketplaceId, null, null, nextToken);
        GetShipmentItemsResult payload = getShipmentItemsResponse.getPayload();
        InboundShipmentItemList itemData = payload.getItemData();
        if(StringUtils.isNotBlank(payload.getNextToken())){
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
            nextToken = payload.getNextToken();
            InboundShipmentItemList shipmentItemsNext = getShipmentItemsNext(fbaInboundApi, marketplaceId, nextToken);
            itemData.addAll(shipmentItemsNext);
        }

        return itemData;
    }

    /**
     * 手动同步FBA货件
     * @param shopId
     * @param shipmentIdList
     * @return
     * @throws ApiException
     */
    public List<TmpFbaShipment> getShipments(Long shopId, List<String> shipmentIdList) throws ApiException {
        InboundShipmentList shipmentData = new InboundShipmentList();

        final ShopInfo shop = shopInfoService.getById(shopId);

        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);
//        List<String> shipmentStatusList = new ArrayList<>();
//        shipmentStatusList.add("WORKING");
//        shipmentStatusList.add("READY_TO_SHIP");
//        shipmentStatusList.add("SHIPPED");
//        shipmentStatusList.add("RECEIVING");
//        shipmentStatusList.add("CANCELLED");
//        shipmentStatusList.add("DELETED");
//        shipmentStatusList.add("CLOSED");
//        shipmentStatusList.add("IN_TRANSIT");
//        shipmentStatusList.add("DELIVERED");
//        shipmentStatusList.add("CHECKED_IN");

        Calendar cstart=Calendar.getInstance();
        cstart.add(Calendar.DATE, -7);
        FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shop);

        String marketplaceId = shop.getMarketplaceId();

        GetShipmentsResponse getShipmentsResponse = fbaInboundApi.getShipments("SHIPMENT",marketplaceId,null,shipmentIdList,null,null,null);
        GetShipmentsResult payload = getShipmentsResponse.getPayload();
        shipmentData.addAll(payload.getShipmentData());
        if(null != getShipmentsResponse.getPayload() && null != getShipmentsResponse.getPayload().getNextToken()){
            //频繁请求接口会报错
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            InboundShipmentList shipmentsNext = getShipmentsNext(fbaInboundApi, marketplaceId, getShipmentsResponse.getPayload().getNextToken());
            shipmentData.addAll(shipmentsNext);
        }
        //拉取数据完成 映射字段并组装数据
        List<TmpFbaShipment> tmpFbaShipments = buildData(shipmentData,shop);

        return tmpFbaShipments;
    }

    public List<TmpFbaShipmentProduct> getShipmentItems(Long shopId, List<String> shipmentIdList) throws ApiException {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        ShopInfo shop = shopInfoService.getById(shopId);

        FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shop);
        InboundShipmentItemList itemData = new InboundShipmentItemList();

        String marketplaceId = shop.getMarketplaceId();
        for(String shipmentId : shipmentIdList){
            GetShipmentItemsResponse getShipmentItemsResponse = fbaInboundApi.getShipmentItemsByShipmentId(shipmentId,marketplaceId);
            GetShipmentItemsResult payload = getShipmentItemsResponse.getPayload();
            if(null != payload){
                itemData.addAll(payload.getItemData());
                if(null != payload.getNextToken()){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    InboundShipmentItemList shipmentItemsNext = getShipmentItemsNext(fbaInboundApi, marketplaceId, getShipmentItemsResponse.getPayload().getNextToken());
                    itemData.addAll(shipmentItemsNext);
                }
            }
        }

        //数据拉取完成 映射字段并组装数据
        List<TmpFbaShipmentProduct> tmpFbaShipmentProducts = buildItemData(itemData);
        return tmpFbaShipmentProducts;
    }

    /**
     * 获取运输详情
     * @param shopId
     * @param shipmentId
     * @throws ApiException
     */
    public TransportContent getTransportDetails(Long shopId,String shipmentId) throws ApiException {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        ShopInfo shop = shopInfoService.getById(shopId);

        FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shop);
        GetTransportDetailsResponse transportDetails = fbaInboundApi.getTransportDetails(shipmentId);
        if(transportDetails.getPayload() != null){
            return transportDetails.getPayload().getTransportContent();
        }else{
            Assert.isTrue(false,transportDetails.getErrors().getErrors().get(0).getMessage());
        }
        return null;
    }

    /**
     * 向亚马逊发送货件追踪编码
     * @param fbaShipmentVo
     * @throws ApiException
     */
    public void putTransportDetails(FbaShipmentVo fbaShipmentVo) throws ApiException {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        ShopInfo shop = shopInfoService.getById(fbaShipmentVo.getShop());

        FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shop);

        PutTransportDetailsRequest body = new PutTransportDetailsRequest()
                .isPartnered("1".equals(fbaShipmentVo.getCarrier())?true:false)
                .shipmentType(ShipmentType.fromValue(fbaShipmentVo.getShipmenttype()))
                .transportDetails(getTransportDetailInput(fbaShipmentVo));
        try{
            PutTransportDetailsResponse transportDetails = fbaInboundApi.putTransportDetails(fbaShipmentVo.getShipmentId(),body);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    /**
     * 运输信息
     * @param fbaShipmentVo
     * @return
     */
    public TransportDetailInput getTransportDetailInput(FbaShipmentVo fbaShipmentVo){
        TransportDetailInput transportDetailInput = new TransportDetailInput();
        if(fbaShipmentVo.getShipmenttype().equals("SP")){

            NonPartneredSmallParcelPackageInputList list = new NonPartneredSmallParcelPackageInputList();
            for(FbaShipmenttrackItemVo trackItemVo : fbaShipmentVo.getTrackno()){
                NonPartneredSmallParcelPackageInput nonPartneredSmallParcelPackageInput = new NonPartneredSmallParcelPackageInput()
                        .trackingId(trackItemVo.getTrackingnumber());
                list.add(nonPartneredSmallParcelPackageInput);
            }
            // 小包裹快递（SPD）
            NonPartneredSmallParcelDataInput nonPartneredSmallParcelDataInput =
                    new NonPartneredSmallParcelDataInput()
                            .carrierName("Other")
                            .packageList(list);
            transportDetailInput.nonPartneredSmallParcelData(nonPartneredSmallParcelDataInput);
        }else if (fbaShipmentVo.getShipmenttype().equals("LTL")){

            //汽运担 (LTL)
            NonPartneredLtlDataInput nonPartneredLtlDataInput = new NonPartneredLtlDataInput()
                    .carrierName("Other")
                    .proNumber(fbaShipmentVo.getReferenceId());
            transportDetailInput.setNonPartneredLtlData(nonPartneredLtlDataInput);
        }else {
            throw new RException("货件类型错误");
        }
        return transportDetailInput;
    }

    /**
     * 更新发货
     * @param fbaShipmentVo
     * @throws ApiException
     */
    public void updateInboundShipment(FbaShipmentVo fbaShipmentVo) throws ApiException {

        final ShopInfo shopInfo = shopInfoService.getById(fbaShipmentVo.getShop());

        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shopInfo);

        InboundShipmentResponse response = fbaInboundApi.updateInboundShipment(getInboundShipmentRequest(fbaShipmentVo,shopInfo,ShipmentStatus.SHIPPED), fbaShipmentVo.getShipmentId());
        Assert.isNull(response.getErrors(),"更新货件异常！");
    }

    /**
     * 删除货件
     * @param fbaShipmentVo
     * @throws ApiException
     */
    public void deleteInboundShipment(FbaShipmentVo fbaShipmentVo) throws ApiException {

        final ShopInfo shopInfo = shopInfoService.getById(fbaShipmentVo.getShop());

        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        FbaInboundApi fbaInboundApi = amazonUtil.getFbaInboundApi(entityAuthority,shopInfo);

        InboundShipmentResponse response = fbaInboundApi.updateInboundShipment(getInboundShipmentRequest(fbaShipmentVo,shopInfo,ShipmentStatus.DELETED), fbaShipmentVo.getShipmentId());

        Assert.isNull(response.getErrors(),"删除货件异常！");
    }

    /**
     * 获取请求参数
     * @param fbaShipmentVo
     * @param shopInfo
     * @return
     */
    public InboundShipmentRequest getInboundShipmentRequest(FbaShipmentVo fbaShipmentVo,ShopInfo shopInfo,ShipmentStatus shipmentStatus){
        InboundShipmentRequest body = new InboundShipmentRequest()
                .inboundShipmentHeader(getInboundShipmentHeader(fbaShipmentVo,shipmentStatus))
                .inboundShipmentItems(getInboundShipmentItems(fbaShipmentVo.getList()))
                .marketplaceId(shopInfo.getMarketplaceId());
        return body;
    }

    /**
     * 入站发货信息，用于更新入站发货
     * @param fbaShipmentVo
     * @return
     */
    public InboundShipmentHeader getInboundShipmentHeader(FbaShipmentVo fbaShipmentVo,ShipmentStatus shipmentStatus){
        final SysCountry country = sysCountryService.getById(fbaShipmentVo.getShipmentsCountry());
        Address address = new Address();
        address.setName(fbaShipmentVo.getConsignerName()); //个人或企业的名称
        address.setAddressLine1(fbaShipmentVo.getStreetAddress()); //街道地址信息
        address.setCity(fbaShipmentVo.getCity()); //城市
//        address.setDistrictOrCounty(""); //区或县(非必填)
        address.setStateOrProvinceCode(fbaShipmentVo.getProvince()); //州或省的代码
        address.setCountryCode(country.getCode()); //国家编码
        address.setPostalCode(fbaShipmentVo.getPostcode()); //邮编

        InboundShipmentHeader inboundShipmentHeader = new InboundShipmentHeader()
                .shipmentName(fbaShipmentVo.getShipmentName())
                .shipFromAddress(address)
                .destinationFulfillmentCenterId(fbaShipmentVo.getDestinationFulfillmentCenterId())
//                .areCasesRequired(false)
                .shipmentStatus(shipmentStatus)
                .labelPrepPreference(LabelPrepPreference.fromValue(fbaShipmentVo.getLabelType()))
                .intendedBoxContentsSource(IntendedBoxContentsSource._2D_BARCODE);

        return inboundShipmentHeader;
    }

    /**
     * 入境装运项目信息的列表
     * @param list
     * @return
     */
    public InboundShipmentItemList getInboundShipmentItems(List<FbaShipmentProductItemVo> list){
        InboundShipmentItemList inboundShipmentItems = new InboundShipmentItemList();
        for(FbaShipmentProductItemVo vo : list){
            InboundShipmentItem item = new InboundShipmentItem()
                    .sellerSKU(vo.getMsku())
                    .quantityShipped(vo.getQuantityShippedLocal()) //数量
                    .quantityInCase(vo.getQuantityPerCarton()); //每个箱子中的物品数量（非必填）
            inboundShipmentItems.add(item);
        }
        return inboundShipmentItems;
    }

}
